part of "../taobao.dart";

/// 用class表示而非Raw格式的淘宝订单
class TaobaoTrade {
  /// 实付金额
  double payment;

  /// 订单的创建时间（提交时间）
  DateTime createTime;

  /// 订单付款时间
  DateTime? payTime;

  /// 买家id（加密后的，真实的旺旺号无法查看）
  String buyerId;

  /// 订单编号
  String orderId;

  /// 交易状态
  String status;

  /// 订单中的所有商品
  List<TaobaoSku> skus;

  TaobaoTrade({
    required this.payTime,
    required this.payment,
    required this.createTime,
    required this.buyerId,
    required this.orderId,
    required this.status,
    required this.skus,
  });

  factory TaobaoTrade.fromRaw(Json raw) {
    print(jsonEncode(raw));
    return TaobaoTrade(
      payTime: DateTime.tryParse(raw["pay_time"] ?? ""),
      payment: double.parse(raw["payment"]),
      createTime: DateTime.parse(raw["created"]),
      buyerId: raw["buyer_open_uid"],
      orderId: raw["tid"],
      status: raw["status"],
      skus: (raw["orders"]["order"] as JsonList)
          .unzip((raw) => TaobaoSku.fromRaw(raw)),
    );
  }
}

class TaobaoSku {
  /// 数量
  int number;

  /// 实付金额
  double payment;

  /// sku的商家编码
  String skuId;

  /// 退款状态
  String refundStatus;

  TaobaoSku({
    required this.number,
    required this.skuId,
    required this.refundStatus,
    required this.payment,
  });

  factory TaobaoSku.fromRaw(Json raw) => TaobaoSku(
        number: raw["num"],
        skuId: raw["outer_sku_id"],
        refundStatus: raw["refund_status"],
        payment: double.parse(raw["payment"]),
      );
}

/// 在orderJson["status"]中会有一段字符串，标记了订单可能的状态
/// 此处为了防止错拼，因此使用enum来表示
enum TaobaoOrderStatus {
  // 订单刚刚创建，并未付款，此时不需要管
  created("WAIT_BUYER_PAY"),
  // 订单已支付，但并未发货
  paid("WAIT_SELLER_SEND_GOODS"),
  // 订单已发货（因此是等待买家确认收货）
  // 此时如果有游戏化产品，那么它将自动被激活
  sent("WAIT_BUYER_CONFIRM_GOODS"),
  // 此状态代表已收款，之后可能会用到
  succeed("TRADE_FINISHED"),
  // 订单无论被淘宝关闭，还是买家自己关闭都一样
  // 但是淘宝使用了2个字段来表示
  closedByTaobao("TRADE_CLOSED_BY_TAOBAO"),
  closed("TRADE_CLOSED");

  final String value;
  const TaobaoOrderStatus(this.value);
}
